<template>
  <ion-page>
    <ion-header :translucent="true">
      <ion-toolbar>
        <ion-title>Ionic Vue - Push Notification</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">Ionic Vue - Push Notification</ion-title>
        </ion-toolbar>
      </ion-header>

      <div id="container">
        <strong>FCM Token</strong><br>
        <ion-button @click="showToken()">Show token</ion-button>
        <p class="selectext" v-if="viewToken">{{ token }}</p>
      </div>
      <div>
        <ion-button @click="stopMusic()">stop music</ion-button>
      </div>
    </ion-content>
  </ion-page>
</template>

<script lang="ts">
import {IonContent, IonHeader, IonPage, IonTitle, IonToolbar} from '@ionic/vue';
import {defineComponent} from 'vue';
import {FCM} from '@capacitor-community/fcm';
import {PushNotifications} from '@capacitor/push-notifications';
import {NativeAudio} from '@capgo/native-audio';
import {App, VolumeDirection} from '@capacitor-rydeen/app';

export default defineComponent({
  name: 'HomePage',
  components: {
    IonContent,
    IonHeader,
    IonPage,
    IonTitle,
    IonToolbar
  },
  data() {
    return {
      token: '',
      viewToken: false
    }
  },
  mounted() {
    // // Check the device with getPlatorms
    // console.log("Ionic platform is: " + getPlatforms());
    //
    // // Check the device with Capacitor
    // const device = Capacitor.getPlatform();
    // console.log("Capacitor platform is: " + device);

    const registerNotifications = async () => {
      let permStatus = await PushNotifications.checkPermissions();

      if (permStatus.receive === 'prompt') {
        permStatus = await PushNotifications.requestPermissions();
      }

      if (permStatus.receive !== 'granted') {
        throw new Error('User denied permissions!');
      }

      await PushNotifications.register();

      FCM.subscribeTo({topic: "test"})
          .then(() => alert(`subscribed to topic`))
          .catch((err) => console.log(err));

      // FCM.unsubscribeFrom({topic: "test"});//取消订阅
    }


    const addListeners = async () => {
      await PushNotifications.addListener('pushNotificationReceived', notification => {
        // let data = JSON.parse(notification.data);

        //播放十次，等待前一次结束再播放
        (async () => {
          const total_count = 10;
          let count = 0;
          await NativeAudio.addListener("complete", () => {
            if (count < total_count - 1) {//由于下面会触发一次所以这边要减1
              NativeAudio.play({
                assetId: "fire"
              })
              App.adjustVolume({
                direction: VolumeDirection.UP
              });
              count++;
            }
          })
          await NativeAudio.play({
            assetId: "fire"
          })
        })();

        console.log('Push notification received: ', notification);
      });

      await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
        console.log('Push notification action performed', notification.actionId, notification.inputValue);
      });
    }

    // const getDeliveredNotifications = async () => {
    //   const notificationList = await PushNotifications.getDeliveredNotifications();
    //   console.log('delivered notifications', notificationList);
    // }


    // 注册
    registerNotifications()
    // 添加监听
    addListeners()

    // // 获取已送达通知
    // getDeliveredNotifications()

    //此方法将把更优化的背景音频文件加载到内存中
    NativeAudio.preload({
      assetId: "fire",
      assetPath: "assets/sounds/fire.mp3",
      audioChannelNum: 1,
      volume: 0.1,
      isUrl: false
    });

  },
  methods: {
    async showToken() {
      this.token = await FCM.getToken().then(function (result: any) {
        console.log(result);
        return result
      }, function (err) {
        console.log(err);
        return err
      });
      this.viewToken = true;
    },
    async stopMusic() {
      await NativeAudio.stop({
        assetId: "fire"
      });
    },
  },
});
</script>

<style scoped>
#container {
  text-align: center;

  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

#container strong {
  font-size: 20px;
  line-height: 26px;
}

#container p {
  font-size: 16px;
  line-height: 22px;

  color: #8c8c8c;

  margin: 0;
}

#container a {
  text-decoration: none;
}

.selectext {
  -webkit-user-select: auto;
}
</style>